// https://www.lintcode.com/problem/maximum-binary-tree/my-submissions

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */

class Solution {
public:
    /**
     * @param nums: an array
     * @return: the maximum tree
     */
    TreeNode * helper(vector<int> &nums, int begin, int end) {
        if(begin > end) return NULL;
        int maxIdx = begin;
        int maxVal = INT_MIN;
        for (int i = begin; i <= end; ++i)
        {
            if (nums[i] > maxVal)
            {
                maxVal = nums[i];
                maxIdx = i;
            }
        }
        TreeNode *root = new TreeNode(maxVal);
        // if (maxIdx > begin) 
        // {
        root->left = helper(nums, begin, maxIdx - 1);
        // }
        // else root->left = NULL;
        // if (maxIdx < end - 1)  //不要搞这些繁琐的，直接在开头判断
        // {
        root->right = helper(nums, maxIdx + 1, end);
        // }
        // else root->right = NULL;
        return root;
    }
    TreeNode * constructMaximumBinaryTree(vector<int> &nums) {
       return helper(nums, 0, nums.size() - 1); // 这边就定义成n-1，以防内部出错
    }
};